<style>
    .layui-form-label {
        width: 100px;
    }

    .layui-input-block {
        margin-left: 130px;
    }
</style>
<!-- 正文开始 -->
<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-card-body">
            <!-- 头部操作栏 -->
            <div class="layui-form lay-header">
                <div class="toolbar">
                    <div class="layui-form-item lay-query-content">
                        <div class="lay-query-box">
                            <div class="query-lt">
                                <div class="layui-inline">
                                    <label class="layui-form-label w-auto">名称：</label>
                                    <div class="layui-input-inline">
                                        <input name="name" class="layui-input" type="text" placeholder="请输入名称"/>
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <button class="layui-btn icon-btn color-green" lay-filter="formSubSearchLog"
                                            lay-submit layui-form-keyDownSearch="true">查询
                                    </button>
                                    <button class="layui-btn icon-btn color-white" lay-filter="resets" lay-submit>重置
                                    </button>
                                </div>
                            </div>
                            <div class="query-rt"></div>
                        </div>
                    </div>
                </div>
                <div class="lay-btn-rows">
                    <div class="lay-btn-box">
                        <div class="lay-btn-lt">
                            <button id="productWorkmanshipBtnAdd" class="layui-btn icon-btn color-reseda">添加</button>
                        </div>
                        <div class="lay-btn-rt">

                        </div>
                    </div>
                </div>
            </div>
            <!-- 表格 -->
            <div class="table-bor">
                <table class="layui-table" id="systemMsgCategoryTable" lay-filter="systemMsgCategoryTable"></table>
            </div>
        </div>
    </div>
</div>

<!-- 表格操作列 -->
<script type="text/html" id="systemMsgCategoryTableBar">
    <a class="layui-btn layui-btn-warm layui-btn-xs" lay-event="edit">修改</a>
    <!--<a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="addSub">添加子分类</a>-->
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>

<!-- 表单弹窗 -->
<script type="text/html" id="systemMsgCategoryForm">
    <form lay-filter="systemMsgCategoryForm" class="layui-form open-form">
        <div class="open-model">
            <div class="open-auto">
                <input name="id" type="hidden"/>
                <div class="layui-form-item" id="PID">
                    <label class="layui-form-label">所属科目分类</label>
                    <input name="subId" type="hidden"/>
                    <div class="layui-input-block" id="selectCategory">
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">参数项名称</label>
                    <div class="layui-input-block">
                        <input name="name" placeholder="请输入名称" type="text" class="layui-input" lay-verify="required"
                               required/>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">参数呈现方式</label>
                    <div class="layui-input-block">
                        <select name="type" lay-filter="type">
                            <option value="radio">单选</option>
                            <option value="check">复选</option>
                            <option value="text">文本框</option>
                            <option value="date">日期</option>
                            <option value="time">时间</option>
                        </select>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">描述</label>
                    <div class="layui-input-block">
                        <textarea id="remark" name="remark" placeholder="请输入描述" class="layui-textarea"/>
                    </div>
                </div>
                <div class="layui-form-item" id="btnAddDiv">
                    <label class="layui-form-label"></label>
                    <div class="layui-input-inline">
                        <button id="btnAdd" class="layui-btn" lay-filter="btnAdd" onclick="return false;">添加选择项</button>
                    </div>
                </div>

                <div class="layui-form-item" id="textParamDiv" style="display: none">
                    <label class="layui-form-label">文本参数</label>
                    <div class="layui-input-block">
                        <input name="textParam" placeholder="请输入文本参数" type="text" class="layui-input"/>
                    </div>
                </div>

                <div class="layui-form-item" id="dateParamDiv" style="display: none">
                    <label class="layui-form-label">日期参数</label>
                    <div class="layui-input-block">
                        <input id="dateParam" name="dateParam" placeholder="请输入日期参数" type="text" class="layui-input"/>
                    </div>
                </div>

                <div class="layui-form-item" id="timeParamDiv" style="display: none">
                    <label class="layui-form-label">时间参数</label>
                    <div class="layui-input-block">
                        <input id="timeParam" name="timeParam" placeholder="请输入时间参数" type="text" class="layui-input"/>
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">排序</label>
                    <div class="layui-input-block">
                        <input name="sortNumber" placeholder="请输入排序" type="text" class="layui-input" lay-verify=""
                               required/>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">是否启用</label>
                    <div class="layui-input-block">
                        <input name="isDeleted" type="checkbox" lay-skin="switch" value="1" checked="false"
                               lay-text="启用|停用"/>
                    </div>
                </div>
            </div>
            <div class="layui-form-item text-right">
                <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">取消</button>
                <button class="layui-btn" lay-filter="systemMsgCategoryFormSubmit" lay-submit>保存</button>
            </div>
        </div>
    </form>
</script>

<script type="text/html" id="childForm">
    <form lay-filter="systemMsgCategoryForm" class="layui-form model-form">
        <input name="id" type="hidden"/>
        <input name="subId" type="hidden"/>
        <div class="layui-form-item">
            <label class="layui-form-label">名称</label>
            <div class="layui-input-block">
                <input name="name" placeholder="请输入名称" type="text" class="layui-input" lay-verify="required"
                       required/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">描述</label>
            <div class="layui-input-block">
                <textarea name="remark" placeholder="请输入描述" class="layui-textarea"/>
            </div>
        </div>

        <!--<div class="layui-form-item">
            <label class="layui-form-label">科目参数类型</label>
            <div class="layui-input-block">
                <select name="type">
                    <option value="radio">单选</option>
                    <option value="check">复选</option>
                    <option value="text">文本框</option>
                    <option value="img">上传图片</option>
                </select>
            </div>
        </div>-->
        <div class="layui-form-item">
            <label class="layui-form-label">排序</label>
            <div class="layui-input-block">
                <input name="sortNumber" placeholder="请输入排序" type="text" class="layui-input" lay-verify=""
                       required/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">是否启用</label>
            <div class="layui-input-block">
                <input name="isDeleted" type="checkbox" lay-skin="switch" value="1" checked="false"
                       lay-text="启用|停用"/>
            </div>
        </div>


        <div class="layui-form-item text-right">
            <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">取消</button>
            <button class="layui-btn" lay-filter="childFormSubmit" lay-submit>保存</button>
        </div>
    </form>
</script>

<!-- js部分 -->
<script>
    layui.use(['layer', 'form', 'table', 'laydate', 'admin', 'laytpl', 'tableTreeDj', 'config'], function () {
        var $ = layui.jquery;
        var layer = layui.layer;
        var form = layui.form;
        var table = layui.table;
        var config = layui.config;
        var admin = layui.admin;
        var tableTree = layui.tableTreeDj;
        var laydate = layui.laydate;
        var TreeData = [];
        var i = 0;

        // 渲染表格
        var insTb = table.render({
            id: '#systemMsgCategoryTable',
            elem: '#systemMsgCategoryTable',
            url: config.base + 'enterprise/purchase/admin/supplierDueSubject/list',
            toolbar: true,
            defaultToolbar: ["filter"],
            page: false,
            cellMinWidth: 100,
            cols: [[
                {type: 'numbers'}
                , {field: 'name', title: '科目名称'}
                , {field: 'categoryName', title: '所属科目分类'}
                , {
                    field: 'type', title: '科目属性类型', templet: function (d) {
                        if (d.type === 'radio') {
                            return '单选'
                        } else if (d.type === 'check') {
                            return '复选'
                        } else if (d.type === 'text') {
                            return '文本框'
                        } else if (d.type === 'date') {
                            return '日期'
                        } else if (d.type === 'time') {
                            return '时间'
                        }
                    }
                }
                , {field: 'remark', title: '描述'}
                , {
                    field: 'isDeleted', title: '是否启用', templet: function (d) {
                        if (d.isDeleted) {
                            return '<input name="isDeleted" type="checkbox" lay-skin="switch" value="' + d.id + '" checked="' + d.isDeleted + '" lay-filter="isDeleted"  lay-text="启用|停用"/>';
                        } else {
                            return '<input name="isDeleted" type="checkbox" lay-skin="switch" value="' + d.id + '" lay-filter="isDeleted"   lay-text="启用|停用"/>';
                        }
                    }
                }
                , {field: 'createTime', sort: true, title: '创建时间'}
                , {field: 'sortNumber', sort: true, title: '排序'}
                , {align: 'center', toolbar: '#systemMsgCategoryTableBar', title: '操作', width: 210}
            ]]
        });

        // 工具条点击事件
        table.on('tool(systemMsgCategoryTable)', function (obj) {
            var data = obj.data;
            if (obj.event === 'edit') { //修改
                showEditModel(data, 'systemMsgCategoryForm', 'systemMsgCategoryFormSubmit');
            } else if (obj.event === 'del') { // 删除
                doDelete(obj);
            } else if (obj.event === 'addSub') {
                //添加子级分类
                showEditModel(data, 'childForm', 'childFormSubmit', data.id);
            }
        });

        //监听排序
        table.on('sort(systemMsgCategoryTable)', function (obj) {
            table.reload('systemMsgCategoryTable', {
                initSort: obj
                , where: {
                    sort: obj.field
                    , order: obj.type
                }
            });
        });

        // 搜索
        form.on('submit(formSubSearchLog)', function (data) {
            insTb.reload({where: data.field, page: {curr: 1}}, 'data');
        });

        // 重置搜索
        form.on('submit(resets)', function (data) {
            insTb.reload({where: admin.resetSearch(data.field), page: {curr: 1}}, 'data');
        });


        form.on('switch(isDeleted)', function (obj) {
            if (obj.elem.checked) {
                enable(obj.value)
            } else {
                disable(obj.value)
            }
        })

        //是否启用
        function enable(id) {
            admin.req('enterprise/purchase/admin/supplierDueSubject/enable', {id: id}, function (res) {
                if (res.code == 200) {
                    layer.msg(res.msg, {icon: 1});
                    insTb.reload('systemMsgCategoryTable');
                } else {
                    layer.msg(res.msg, {icon: 2});
                }
            }, 'POST');
        }

        //是否停用
        function disable(id) {
            admin.req('enterprise/purchase/admin/supplierDueSubject/disable', {id: id}, function (res) {
                if (res.code == 200) {
                    layer.msg(res.msg, {icon: 1});
                    insTb.reload('systemMsgCategoryTable');
                } else {
                    layer.msg(res.msg, {icon: 2});
                }
            }, 'POST');
        }

        // 添加按钮点击事件
        $('#productWorkmanshipBtnAdd').click(function () {
            showEditModel(undefined, 'systemMsgCategoryForm', 'systemMsgCategoryFormSubmit');
        });

        // 显示编辑弹窗
        function showEditModel(data, formId, submitButton, subIdVal) {
            console.info(data, 9090);
            if(data != undefined){
                if (data.value === 'radio') {
                    $("#btnAdd").hide();
                    $("#paramDiv").show();
                    $("#value0").show();
                    $("#textParamDiv").hide();
                    $("#dateParamDiv").hide();
                    $("#timeParamDiv").hide();
                } else if (data.value === 'check') {
                    $("#btnAdd").show();
                    $("#paramDiv").show();
                    $("#value0").show();
                    $("#textParamDiv").hide();
                    $("#dateParamDiv").hide();
                    $("#timeParamDiv").hide();
                } else if (data.value === 'text') {
                    $("#btnAdd").hide();
                    $("#paramDiv").hide();
                    $("#value0").hide();
                    $("#textParamDiv").show();
                    $("#dateParamDiv").hide();
                    $("#timeParamDiv").hide();
                } else if (data.value === 'date') {
                    $("#btnAdd").hide();
                    $("#paramDiv").hide();
                    $("#value0").hide();
                    $("#textParamDiv").hide();
                    $("#dateParamDiv").show();
                    $("#timeParamDiv").hide();
                } else if (data.value === 'time') {
                    $("#btnAdd").hide();
                    $("#paramDiv").hide();
                    $("#value0").hide();
                    $("#textParamDiv").hide();
                    $("#dateParamDiv").hide();
                    $("#timeParamDiv").show();
                }
            }
            let finalCategoryIds = [];
            form.on("select(type)", function (data) {
                if (data.value === 'radio') {
                    $("#btnAdd").hide();
                    $("#paramDiv").show();
                    $("#value0").show();
                    $("#textParamDiv").hide();
                    $("#dateParamDiv").hide();
                    $("#timeParamDiv").hide();
                } else if (data.value === 'check') {
                    $("#btnAdd").show();
                    $("#paramDiv").show();
                    $("#value0").show();
                    $("#textParamDiv").hide();
                    $("#dateParamDiv").hide();
                    $("#timeParamDiv").hide();
                } else if (data.value === 'text') {
                    $("#btnAdd").hide();
                    $("#paramDiv").hide();
                    $("#value0").hide();
                    $("#textParamDiv").show();
                    $("#dateParamDiv").hide();
                    $("#timeParamDiv").hide();
                } else if (data.value === 'date') {
                    $("#btnAdd").hide();
                    $("#paramDiv").hide();
                    $("#value0").hide();
                    $("#textParamDiv").hide();
                    $("#dateParamDiv").show();
                    $("#timeParamDiv").hide();
                } else if (data.value === 'time') {
                    $("#btnAdd").hide();
                    $("#paramDiv").hide();
                    $("#value0").hide();
                    $("#textParamDiv").hide();
                    $("#dateParamDiv").hide();
                    $("#timeParamDiv").show();
                }
            });
            admin.open({
                type: 1,
                area: ['660px', '76%'],
                offset: '65px',
                title: subIdVal ? '添加子分类' : (data ? '编辑尽调科目' : '添加尽调科目'),
                content: $('#' + formId).html(),
                success: function () {
                    function treeEach(treeData, ids) {
                        $.each(treeData, function (i, val) {
                            if (customContains(ids, val.value)) {
                                val.disabled = true;
                            }
                            if (val.children && val.children.length > 0) {
                                treeEach(val.children, ids);
                            }
                        });
                    }

                    //日期参数
                    laydate.render({
                        elem: '#dateParam'
                        , type: 'date'
                        , format: 'yyyy-MM-dd'
                    });

                    //时间参数
                    laydate.render({
                        elem: '#timeParam'
                        , type: 'datetime'
                    });


                    let customContains = function (box, val) {
                        for (let i = 0; i < box.length; i++) {
                            if (box[i] == val) {
                                return true;
                            }
                        }
                        return false;
                    };


                    if (data && data.subId) {
                        $.each(TreeData, function (i, val) {
                            if (val.value == data.subId) {
                                val.selected = true;
                            }
                        });
                    }


                    var getTemplateHtml = function (i, value, update) {
                        var labelName = '';
                        var valLen = $("form input[name='value']").length;
                        var classNew = '';
                        if (valLen == 0) {
                            labelName = '参数值';
                        } else {
                            classNew = 'newAdd'
                        }
                        var inputHtml = "";
                        if (update) {
                            inputHtml = '<input id="value' + i + '" name="paramValue" value="' + value + '" placeholder="请输入参数" type="text" class="layui-input" lay-verify=""/>';
                        } else {
                            inputHtml = '<input id="value' + i + '" name="paramValue" placeholder="请输入参数" type="text" class="layui-input" lay-verify=""/>'
                        }
                        console.log(inputHtml)
                        var templateHtml = '' +
                            '<div class="layui-form-item ' + classNew + '" id = "paramDiv">' +
                            '<div class="layui-form-item">' +
                            '<div >' +
                            '<label class="layui-form-label" >' + labelName + '</label>' +
                            '<div class="layui-input-inline">' +
                            inputHtml +
                            '</div>' +
                            '</div>' +
                            '<div >' +

                            // '<div class="layui-input-inline">' +
                            // '<input id="sort'+i+'" name="sort" placeholder="排序值" type="text" class="layui-input" lay-verify="sortNumber" required/>' +
                            // '</div>' +
                            '</div>';

                        templateHtml += '<div class="layui-input-inline">' +
                            '<button id="btnDel' + i + '" class="layui-btn delBtn" lay-filter="btnDel' + i + '" style="margin-left: 20px;">删除</button>' +
                            '</div>';
                        templateHtml += '</div>' + '</div>';
                        return templateHtml;
                    }


                    var addTemplateDiv = function (value, update) {
                        var html = getTemplateHtml(i++, value, update);
                        $("#btnAddDiv").prev().after(html);
                        form.render();
                        // btnCount++;
                        form.render('select');

                        $(".delBtn").off('click').on('click', function () {
                            var btn = $(this);
                            var btnId = btn[0].id;
                            var btnNo = btnId.substring("btnDel".length, btnId.length);
                            btn.parent().parent().parent().remove();
                        });
                    };

                    if (formId != 'childForm') {
                        var json = {};
                        if (data && data.subId) {
                            json.selectId = data.subId;
                        }

                        admin.req('enterprise/purchase/admin/supplierDueSubjectCategory/getTreeData', json, function (obj) {
                            TreeData = obj.data;

                            xmSelect.render({
                                el: '#selectCategory',
                                model: {label: {type: 'text'}},
                                radio: true,
                                clickClose: true,
                                filterable: true,
                                tree: {
                                    show: true,
                                    strict: false,
                                    /*expandedKeys: [-1],*/
                                    expandedKeys: true,
                                },
                                tips: '顶级分类',
                                height: 'auto',
                                data() {
                                    return TreeData;
                                },
                                on: function (data) {
                                    //被选中的select的id,如果没有 -1
                                    let subId = data.arr.length > 0 ? data.change[0].value : -1;
                                    $("input[name='subId']").val(subId);
                                },
                            });
                        }, 'GET');
                    }

                    $('#btnAdd').click(addTemplateDiv);


                    if (data == undefined || (data && (data.eventType == 'addSpec' || data.eventType == 'addSpecFromSpecTable'))) {
                        addTemplateDiv();
                        $("#btnDel0").hide();
                    }
                    //data 非空取值names
                    if (!config.isEmptyObject(data)) {
                        data.name = data.name.indexOf("</span>") > 0 ? data.name.split("</span>")[1] : data.name;
                        data.name = data.name.indexOf("&nbsp; &nbsp;") > 0 ? data.name.split(" &nbsp; &nbsp;").length > 2 ? data.name.split(" &nbsp; &nbsp;")[2] : data.name.split(" &nbsp; &nbsp;")[1] : data.name;
                    }

                    //添加子级渲染所属分类
                    if (formId == 'childForm') {
                        data.code = '';
                        data.name = '';
                        data.description = '';
                        data.status = '';
                        // form.val(formId, data);
                        $("form input[name='subId']").val(data.id);
                        data = undefined;
                    }

                    form.val('systemMsgCategoryForm', data);
                    if (data !== undefined && data !== null) {
                        var paramValues = data.paramValue.split(",");
                        paramValues.forEach(function (value) {
                            addTemplateDiv(value, true);
                        })
                    }

                    // 表单提交事件
                    form.on('submit(' + submitButton + ')', function (d) {
                        layer.load(2);
                        if (d.field.subId == null || d.field.subId == '') {
                            d.field.subId = -1
                        }
                        var isDeleted = $("form input[name='isDeleted']").prop("checked");
                        if (!isDeleted) {
                            d.field.isDeleted = false;
                        } else {
                            d.field.isDeleted = true;
                        }
                        var paramValue = [];

                        $("form input[name='paramValue']").each(function () {
                            paramValue.push($(this).val());
                        });

                        d.field.paramValue = paramValue.toString();
                        admin.req(data ? 'enterprise/purchase/admin/supplierDueSubject/update' : 'enterprise/purchase/admin/supplierDueSubject/add', d.field, function (res) {
                            layer.closeAll('loading');
                            if (res.code == 200) {
                                layer.msg(res.msg, {icon: 1});
                                insTb.reload('systemMsgCategoryTable');
                                layer.closeAll('page');
                            } else {
                                layer.msg(res.msg, {icon: 2});
                            }
                        }, data ? 'PUT' : 'POST');
                        return false;
                    });
                }
            });
        }

        // 删除
        function doDelete(obj) {
            layer.confirm('确定要删除吗？', {
                offset: '65px',
                skin: 'layui-layer-admin'
            }, function (i) {
                layer.close(i);
                layer.load(2);
                admin.req('enterprise/purchase/admin/supplierDueSubject/' + obj.data.id, {}, function (res) {
                    layer.closeAll('loading');
                    if (res.code == 200) {
                        layer.msg(res.msg, {icon: 1});
                        obj.del();
                        insTb.reload('systemMsgCategoryTable');
                    } else {
                        layer.msg(res.msg, {icon: 2});
                    }
                }, 'DELETE');
            });
        }

        // 导出excel
        $('#productCategoryBtnExport').click(function () {
            var checkRows = table.checkStatus('systemMsgCategoryTable');
            if (checkRows.data.length == 0) {
                layer.msg('请选择要导出的数据', {icon: 2});
            } else {
                table.exportFile(insTb.config.id, checkRows.data, 'xls');
            }
        });

    });
</script>